import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:moose_app/core/utils/navigate_util.dart';
import 'package:moose_app/ui/screens/scan_login/scan_login_screen.dart';
import 'package:moose_app/ui/values/colors.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

/// 二维码扫描
class ATHQrScanScreen extends StatefulWidget {
  static final String routeName = "app://qrScan";

  @override
  _ATHQrScanScreenState createState() => _ATHQrScanScreenState();
}

class _ATHQrScanScreenState extends State<ATHQrScanScreen> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'ATHQrScan');

  Barcode result;

  QRViewController controller;

  bool scanSuccess = false;
  bool isJump = false;

  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    } else if (Platform.isIOS) {
      controller.resumeCamera();
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
        scanSuccess = true;
      });
      if (scanSuccess && !isJump) {
        _jumpScanLogin();
      }
    });
  }

  void _jumpScanLogin() {
    setState(() {
      isJump = true;
    });
    ATHNavigator.pushModal(context, ATHScanLoginScreen.routeName);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
          AppBar(title: Text("扫描二维码"), centerTitle: false, actions: <Widget>[]),
      body: mounted
          ? Column(
              children: <Widget>[
                Expanded(
                  flex: 5,
                  child: QRView(
                    key: qrKey,
                    overlay:
                        QrScannerOverlayShape(borderColor: kColorPrimaryLight),
                    onQRViewCreated: _onQRViewCreated,
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Center(
                    child: (result != null)
                        ? Text(
                            'Barcode Type: ${describeEnum(result.format)}   Data: ${result.code}')
                        : Text('Scan a code'),
                  ),
                )
              ],
            )
          : EasyLoading.show(),
    );
  }
}
